﻿package gwdflash.display{
	import flash.utils.*;
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.geom.ColorTransform;
	import flash.text.TextFormat;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFieldAutoSize;
	import flash.events.MouseEvent;
	import flash.events.FocusEvent;
	
	public class FormMail extends MovieClip{
		private var inputs:Object;
		private var failWarning;
		private var successWarning;
		private var warningTimer:uint;
		private var formAction:Function;

		public function FormMail(labels:Array, inputTypes:Array, action:Function, sendButton:MovieClip) {
			inputs = new Object();
			failWarning = null;
			successWarning = null;
			formAction = action;
			
			var txtFormat:TextFormat = new TextFormat();
			txtFormat.font = 'Arial';
			txtFormat.size = 14;
			txtFormat.color = 0xaaaaaa;
			txtFormat.align = 'left';
			
			for(var i:int = 0; i < labels.length; i++){
				inputs[i] = new Object();
				inputs[i].required = false;
				inputs[i].textField = new TextField();
				inputs[i].textField.width = 300;
				inputs[i].textField.height = 20;
				inputs[i].textField.y = (i == 0 ? 0 : inputs[i - 1].textField.y + inputs[i - 1].textField.height + 10);
				if(inputTypes[i] == 'number'){
					inputs[i].textField.restrict = '0-9()';
				}else if(inputTypes[i] == 'textArea'){
					inputs[i].textField.height = 100;
					inputs[i].textField.wordWrap = true;
				}
				inputs[i].textField.type = TextFieldType.INPUT;
				inputs[i].textField.border = true;
				inputs[i].textField.borderColor = 0x333333;
				inputs[i].textField.background = true;
				inputs[i].textField.backgroundColor = 0xffffff;
				inputs[i].textField.defaultTextFormat = txtFormat;
				inputs[i].textField.text = labels[i];
				inputs[i].textField.name = labels[i];
				inputs[i].name = labels[i];
				this.addChild(inputs[i].textField);
				inputs[i].textField.addEventListener(FocusEvent.FOCUS_IN, formmailOnFocusHandler);
			}
			if(sendButton != null){
				var sendBt:MovieClip = MovieClip(sendButton);
				sendBt.buttonMode = true;
				sendBt.x = (this.width - sendBt.width) / 2;
				sendBt.y = inputs[labels.length - 1].textField.y + inputs[labels.length - 1].textField.height + 20;
				sendBt.name = "sendButton";
				
				sendBt.addEventListener(MouseEvent.MOUSE_OVER, formBtOverHandler);
				sendBt.addEventListener(MouseEvent.CLICK, sendFormmail);
			
				this.addChild(sendBt);
			}
		}
		
		private function formmailOnFocusHandler(ev:FocusEvent):void{
			ev.currentTarget.removeEventListener(FocusEvent.FOCUS_IN, formmailOnFocusHandler);
			ev.currentTarget.addEventListener(FocusEvent.FOCUS_OUT, formmailFocusOutHandler);
			if(ev.currentTarget.text == ev.currentTarget.name){
				ev.currentTarget.text = "";
				var currentFieldFormat:TextFormat = new TextFormat();
				currentFieldFormat.font = 'Arial';
				currentFieldFormat.size = 14;
				currentFieldFormat.color = 0x333333;
				currentFieldFormat.align = 'left';
				ev.currentTarget.defaultTextFormat = currentFieldFormat;
			}
			var sendButton = this.getChildByName('sendButton');
			if(!sendButton.hasEventListener(MouseEvent.CLICK)){
				clearWarnings();
			}
		}
		
		private function formmailFocusOutHandler(ev:FocusEvent):void{
			ev.currentTarget.removeEventListener(FocusEvent.FOCUS_OUT, formmailFocusOutHandler);
			ev.currentTarget.addEventListener(FocusEvent.FOCUS_IN, formmailOnFocusHandler);
			if(ev.currentTarget.text == ''){
				var currentFieldFormat:TextFormat = new TextFormat();
				currentFieldFormat.font = 'Arial';
				currentFieldFormat.size = 14;
				currentFieldFormat.color = 0xaaaaaa;
				currentFieldFormat.align = 'left';
				ev.currentTarget.defaultTextFormat = currentFieldFormat;
				ev.currentTarget.text = ev.currentTarget.name;
			}
		}
		
		private function formBtOverHandler(e:MouseEvent):void{
			e.currentTarget.removeEventListener(MouseEvent.MOUSE_OVER, formBtOverHandler);
			var colorTransform:ColorTransform = new ColorTransform(0.7, 0.7, 0.7);
			e.currentTarget.transform.colorTransform = colorTransform;
			e.currentTarget.addEventListener(MouseEvent.MOUSE_OUT, formBtOutHandler);
		}
		
		private function formBtOutHandler(e:MouseEvent):void {
			e.currentTarget.removeEventListener(MouseEvent.MOUSE_OUT, formBtOutHandler);
			var colorTransform:ColorTransform = new ColorTransform(1, 1, 1);
			e.currentTarget.transform.colorTransform = colorTransform;
			e.currentTarget.addEventListener(MouseEvent.MOUSE_OVER, formBtOverHandler);
		}
		
		private function sendFormmail(e:MouseEvent):void {
			var emptyFieldError:Boolean = false;
			var sendingData:Object = new Object();
			
			for(var i:String in inputs){
				if(inputs[i].required && (inputs[i].textField.text == inputs[i].textField.name || inputs[i].textField.text == '')){
					emptyFieldError = true;
					inputs[i].textField.backgroundColor = 0xffcccc;
					inputs[i].textField.addEventListener(FocusEvent.FOCUS_IN, unHighlight);
				}else{
					var inputText:String = inputs[i].textField.text;
					
					if(inputText == inputs[i].textField.name){
						inputText = '';
					}
					sendingData[inputs[i].name.toLowerCase()] = inputText;
				}
			}
			
			if(emptyFieldError){
				sendingData = null;
				showWarning(false);
			}else{
				formAction(sendingData);
			}
		}
		
		public function showWarning(sent:Boolean):void {
			if(sent){
				if(successWarning == null){
					var sWarningFormat:TextFormat = new TextFormat();
					sWarningFormat.font = 'Arial';
					sWarningFormat.color = 0xffffff;
					sWarningFormat.size = 16;
					successWarning = new TextField();
					successWarning.defaultTextFormat = sWarningFormat;
					successWarning.background = true;
					successWarning.backgroundColor = 0x008800;
					successWarning.border = true;
					successWarning.borderColor = 0xffffff;
					successWarning.mouseEnabled = false;
					successWarning.selectable = false;
					successWarning.name = 'warning';
					successWarning.autoSize = TextFieldAutoSize.CENTER;
					successWarning.text = "Form successfully sent."
				}
				successWarning.x = (this.root.stage.stageWidth - successWarning.width) / 2;
				successWarning.y = (this.root.stage.stageHeight - successWarning.height) / 2;
				this.parent.addChild(successWarning);
			}else{
				if(failWarning == null){
					var fWarningFormat:TextFormat = new TextFormat();
					fWarningFormat.font = 'Arial';
					fWarningFormat.color = 0xffffff;
					fWarningFormat.size = 16;
					failWarning = new TextField();
					failWarning.defaultTextFormat = fWarningFormat;
					failWarning.background = true;
					failWarning.backgroundColor = 0x880000;
					failWarning.border = true;
					failWarning.borderColor = 0xffffff;
					failWarning.mouseEnabled = false;
					failWarning.selectable = false;
					failWarning.name = 'warning';
					failWarning.autoSize = TextFieldAutoSize.CENTER;
					failWarning.text = "Form not sent. Please, complete correctly the highlighted fields."
				}
				failWarning.x = (this.root.stage.stageWidth - failWarning.width) / 2;
				failWarning.y = (this.root.stage.stageHeight - failWarning.height) / 2;
				this.parent.addChild(failWarning);
			}
			warningTimer = setInterval(clearWarnings, 5000);
			var sendButton = this.getChildByName('sendButton');
			if(sendButton.hasEventListener(MouseEvent.CLICK)){
				sendButton.removeEventListener(MouseEvent.CLICK, sendFormmail);
			}
		}
		
		private function clearWarnings():void {
			clearInterval(warningTimer);
			this.parent.removeChild(this.parent.getChildByName('warning'));
			var sendButton = this.getChildByName('sendButton');
			if(!sendButton.hasEventListener(MouseEvent.CLICK)){
				sendButton.addEventListener(MouseEvent.CLICK, sendFormmail);
			}
		}
		
		private function unHighlight(e:FocusEvent):void {
			e.currentTarget.removeEventListener(FocusEvent.FOCUS_IN, unHighlight);
			e.currentTarget.backgroundColor = 0xffffff;
		}
		
		public function set requiredFields(fields:Array):void {
			for(var i:String in inputs) {
				for(var j:int = 0; j < fields.length; j++){
					if(inputs[i].name == fields[j]){
						inputs[i].required = true;
						inputs[i].textField.text = "*" + inputs[i].textField.text;
						inputs[i].textField.name = "*" + inputs[i].textField.name;
					}
				}
			}
		}
		
		public function set failDialog(dialog:*):void {
			if(!dialog is Sprite || !dialog is TextField) {
				trace('ERROR: the dialog must be a Sprite or a TextField object. _at FormMail/failDialog() setter method.');
			} else {
				failWarning = dialog;
				failWarning.name = 'warning';
			}
		}
		
		public function set successDialog(dialog:*):void {
			if(!dialog is Sprite || !dialog is TextField) {
				trace('ERROR: the dialog must be a Sprite or a TextField object. _at FormMail/successDialog() setter method.');
			} else {
				successWarning = dialog;
				successWarning.name = 'warning';
			}
		}
		public function traceInputs():void{
			for(var key:String in inputs){
				trace(key + "=>" + inputs[key] + "{");
				for(var subkey:String in inputs[key]){
					trace("	" + subkey + '=>' + inputs[key][subkey]);
				}
				trace("}");
			}
		}
	}
}